package pl.com.qapps.datastore.berkeley;

import java.io.IOException;

import pl.com.qapps.datastore.BytesHelper;


import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.sleepycat.bind.EntryBinding;
import com.sleepycat.je.DatabaseEntry;

/**
 * 
 * @author Jakub Dykowski
 *
 */
public class CompleteEntityBinding implements com.sleepycat.bind.EntityBinding<Entity>,
		EntryBinding<Key> {

	@Override
	public Key entryToObject(DatabaseEntry entry) {
		try {
			return BytesHelper.toKey(entry.getData());
		} catch (IOException e) {
			throw new SerializationError(e);
		}
	}

	@Override
	public void objectToEntry(Key object, DatabaseEntry entry) {
		try {
			entry.setData(BytesHelper.serialize(object));
		} catch (IOException e) {
			throw new SerializationError(e);
		}
	}

	@Override
	public Entity entryToObject(DatabaseEntry key, DatabaseEntry data) {
		try {
			return BytesHelper.toEntity(data.getData());
		} catch (IOException e) {
			throw new SerializationError(e);
		}
	}

	@Override
	public void objectToKey(Entity object, DatabaseEntry key) {
		objectToEntry(object.getKey(), key);
	}

	@Override
	public void objectToData(Entity object, DatabaseEntry data) {
		try {
			data.setData(BytesHelper.serialize(object));
		} catch (IOException e) {
			throw new SerializationError(e);
		}
	}

}
